<?php
/**
 * Core_Role_AddForm
 * 
 * @author naspeh
 * @version $Id: AddForm.php 672 2008-06-30 12:08:01Z naspeh $
 */
class Core_Role_AddForm extends Core_Form
{
    /**
     * Инициализация
     *
     * @return Core_Role_AddForm
     */
    public function init()
    {
        $this->addElement('text', 'name', array(
            'required' => true,
            'label'    => 'Логин:',
            'attribs'  => array(
                'class' => 'text span-4',
                'size'  => 16
            ),     
            'validators' => array(
                new Zend_Validate_Alnum(),
                new Zend_Validate_StringLength(2,16),
                new Core_Validate_UsernameExist()
            )
        ));
        $this->addElement('text', 'email', array(
            'required' => true,
            'label'    => 'Email:',
            'attribs'  => array(
                'class' => 'text span-4',
            ),     
            'validators' => array(
                new Zend_Validate_EmailAddress(),
                new Core_Validate_EmailExist()
            )
        ));
        $this->addElement('password', 'password', array(
            'required' => true,
            'label'    => 'Пароль:',
            'attribs'  => array(
                'class' => 'text span-4',
            )
        ));
        $this->addElement('password', 'password_confirm', array(
            'required' => true,
            'label'    => 'Подтверждение пароля:',
            'attribs'  => array(
                'class' => 'text span-4',
            )
        ));
        $this->addElement('text', 'fullname', array(
            'required' => true,
            'label'    => 'Полное имя:',
            'attribs'  => array(
                'class' => 'text span-4',
                'size'  => 32
            ),     
            'validators' => array(
                new Zend_Validate_StringLength(3,32),
                new Zend_Validate_Alnum(true)
            )
        ));
        $this->addSubForm(Core_Table_Roles::getFormParents(), 'parents');
        $acl = Core_Acl::getRegisrty();
        $tableResourcesTypes = new Core_Table_ResourceTypes();
        $role = $tableResourcesTypes->fetchRow(array('name = ?' => 'Core_Acl_Resource_Type'));
        $role = new Core_Acl_Resource_Role($role);
        $acl->active($role);
        if (false !== ($privilege = $acl->getAllowPrivileges(Core_Auth::get('id'), $role, 'is_login')))
        {
            $this->addElement('checkbox', 'is_login', array(
                'label' => $privilege['desc'],
                'checked' => true,
                'decorators' => array(
                    'ViewHelper',
                    array('Label', array('placement'=>'APPEND')),
                    array('HtmlTag', array('tag' => 'div'))
                )
            ));           
        }
        if (false !== ($privilege = $acl->getAllowPrivileges(Core_Auth::get('id'), $role, 'is_system')))
        {
            $this->addElement('checkbox', 'is_system', array(
                'label' => $privilege['desc'],
                'checked' => false,
                'decorators' => array(
                    'ViewHelper',
                    array('Label', array('placement'=>'APPEND')),
                    array('HtmlTag', array('tag' => 'div'))
                )
            ));           
        }         
        $this->addElement('button', 'submit', array(
            'type'     => 'submit',
            'label'    => 'Сохранить',
            'attribs'  => array(
                'class' => 'positive',
                'icon'  => 'tick'
            )
        ));
        return $this;
    }
    /**
     * Возвращает родителей
     *
     * @return array
     */
    public function getParents()
    {
        $tableRoles = new Core_Table_Roles();
        $rowset = $tableRoles->fetchAll('is_system');
        $acl = Core_Acl::getRegisrty();
        $roles = array();
        foreach ($rowset as $role) {
            $resourceRole = new Core_Acl_Resource_Role($role);
            $acl->active($resourceRole);
            if ($acl->isAllowed(Core_Auth::get('id'), $resourceRole)) {
                $roles[$role->id] = $role->name;;
            }
        }
        $result = array(
            'multiOptions' => $roles,
        );
        return $result;
    }
    /**
     * Вторичная валидация
     *
     * @return Core_Role_AddForm
     */
    protected function _setPostValid()
    {
        $this->getElement('password_confirm')->addValidator(new Core_Validate_PasswordConfirm());
        return $this;
    }
    /**
     * Запускает форму на выполнение
     *
     * @return Core_Role_AddForm
     */    
    public function process()
    {
        $values = $this->getValues(true);
        $tableRoles = new Core_Table_Roles();
        $data = array(
            'name' => $values['name'],
            'email' => $values['email'],
            'password' => md5($values['password']),
            'fullname' => $values['fullname'],
            'is_login' => $values['is_login'],
            'is_system' => $values['is_system']
        );
        $db = Core_Db::getInstance();
        $db->beginTransaction();
        $isError = false;
        
        if (false === ($roleId = $tableRoles->insert($data))) {
            $isError = true;
        } else {
            if (is_array($values['parents'])) {
                $tableRolesTies = new Core_Table_RoleTies();
                $dataParent = array('role_id' => $roleId);
                foreach ($values['parents'] as $key => $value) {
                    if ($value) {
                    $dataParent['parent'] = $key;
                        if (false === $tableRolesTies->insert($dataParent)) {
                            $isError = true;
                            break;
                        }
                    }
                }
            }
        }
        if ($isError) {
            $db->rollBack();
            throw new Core_Exception('databaseError#');
        } else {
            $db->commit();
            Core_Message::add('Роль добавлена', Core_Message::TYPE_SUCCESS);            
            Core_Informant::run($data['email'], 'add_role', array(
                'login' => $data['name'],
                'password' => $values['password'],
                'creator_name' => Core_Auth::get('fullname'),
                'creator_email' => Core_Auth::get('email')
            ));
            $this->init();
        }
        return $this;        
    }
}